/**
 * Created by ancheel on 16/4/4.
 */

const sources = module.exports;
const qs = require('qs');
const Render = require('art-template');
const callApi = require('../utils/callApi')

const openServer = 'http://open.guijianyun.com:7200/oauth2';
const serverAuthUri = 'http://localhost:3000/auth';
const appId = 'VjUBI1dVBjex98UYVLpMeMpQiR0tm_J2drw89YnHQ9M';
const secretKey = 'D8XFBIx6s1D4OK9FakL1MspXDPFF3HnsHh_pxd_JjXU';

const allowOpenIds = {
};

const template = '\
<h3>Welcome {{name}}</h3>\
<a href="/sign_out">SignOut</a>\
';


sources.index = async ctx => {
  const {openId} = ctx.session;
  const userInfo = allowOpenIds[openId];

  if(userInfo) {
    ctx.body = Render.render(template, {name: allowOpenIds[openId].name});
    return;
  }
  console.log(`sources.index ${openId}`);
  ctx.redirect(`${openServer}/authorize?${qs.stringify({
    app_id: appId,
    redirect_uri: serverAuthUri,
  })}`)
};

sources.auth = async ctx => {
  const {code} = ctx.request.query;
  console.log(`auth code is ${code}`);

  const {json, error} = await callApi(`${openServer}/access_token`, {
    app_id: appId,
    secret_key: secretKey,
    code,
    redirect_uri: serverAuthUri,
  }, 'POST');
  console.log(`callApi(${openServer}/access_token`,json);
  if(error) {
    ctx.throw(new Error(error));
  }

  const {access_token: accessToken, open_id: openId} = json;
  console.log(`access token is ${accessToken}`);
  const userInfo = allowOpenIds[openId];

  if(userInfo) {
    console.log(`user is signed in, open id is ${openId}`);
    ctx.redirect('/');
    //user sign in
    ctx.session.openId = openId;
    return;
  }

  //get user info with access token
  const {json: newUser, error: e} = await callApi(`${openServer}/user_info`, {
    access_token: accessToken,
  });

  if(e) {
    ctx.throw(new Error(e));
  }

  console.log(`create new user`);
  console.log(newUser);
  allowOpenIds[openId] = newUser;
  ctx.session.openId = openId;
  ctx.redirect('/');
};


sources.signOut = async ctx => {
  ctx.session = null;
  ctx.redirect(`${openServer}/sign_out`);
};